package cn.aylog.service;

import cn.aylog.dao.MoneyDao;
import cn.aylog.pojo.Money;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

public class MoneyService {

    private MoneyDao dao;
    private PlatformTransactionManager transactionManager;

    public void setTransactionManager(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public void setDao(MoneyDao dao) {
        this.dao = dao;
    }

    /*
     * 声明式事务
     */
    public void transfer(Integer t) {
        Money from = dao.getById(1);
        Money to = dao.getById(2);
        from.setMoney(from.getMoney() - t);
        to.setMoney(to.getMoney() + t);
        dao.update(from);
        int a = 1/0;
        dao.update(to);
    }

    /*
     * 编程式事务
     */
    public void transfer2(Integer t) {
        //  getTransaction()用于启动事务，返回TransactionStatus实例对象
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try{
            Money from = dao.getById(1);
            Money to = dao.getById(2);
            from.setMoney(from.getMoney() - t);
            to.setMoney(to.getMoney() + t);
            dao.update(from);
            int a = 1/0;
            dao.update(to);
            transactionManager.commit(status);
        } catch (Exception e) {
            transactionManager.rollback(status);
            e.printStackTrace();
        }

    }

    public void reset() {
        Money from = dao.getById(1);
        Money to = dao.getById(2);
        from.setMoney(1000);
        to.setMoney(1000);
        dao.update(from);
        dao.update(to);
    }
}
